package com.iplant.basic.serviceImpl.dao.bms;

import com.iplant.base.po.OutResult;
import com.iplant.base.po.Pagination;
import com.iplant.base.po.enums.ExceptionTypes;
import com.iplant.base.utils.general.StringUtils;
import com.iplant.base.utils.sql.BaseDAO;
import com.iplant.basic.service.basicenum.bms.BMSWorkMode;
import com.iplant.basic.service.po.bms.BMSEmployee;
import com.iplant.basic.service.po.bms.BMSTeamItem;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

public class BMSTeamItemDAO extends BaseDAO {
    private static BMSTeamItemDAO Instance = null;

    private BMSTeamItemDAO() {
        super();
    }

    private static Logger logger = LoggerFactory.getLogger(BMSTeamItemDAO.class);

    public static BMSTeamItemDAO getInstance() {
        if (Instance == null) {
            Instance = new BMSTeamItemDAO();
        }
        return Instance;
    }

    private int BMS_CheckTeamItemName(BMSEmployee wLoginUser, BMSTeamItem wBMSTeamItem, OutResult<Integer> wErrorCode) {
        int wID = 0;
        wErrorCode.set(0);
        try {

            Map<String, Object> wParams = new HashMap<String, Object>();
            String wSQLText = StringUtils.Format(
                    "Select ID from {0}.bms_teamitem where ID!=:ID " +
                    " and  TeamID=:TeamID and ( Name =:Name  or  (WorkAreaID=:WorkAreaID and StationID=:StationID)) ;",
                    super.getDBName());

            wParams.put("ID", wBMSTeamItem.ID);
            wParams.put("TeamID", wBMSTeamItem.TeamID);
            wParams.put("Name", wBMSTeamItem.Name);
            wParams.put("StationID", wBMSTeamItem.StationID);
            wParams.put("WorkAreaID", wBMSTeamItem.WorkAreaID);
            wSQLText = this.DMLChange(wSQLText);
            List<Map<String, Object>> wQueryResultList = super.queryForList(wSQLText, wParams);
            for (Map<String, Object> wSqlDataReader : wQueryResultList) {
                wID = StringUtils.parseInt(wSqlDataReader.get("ID"));
            }

        } catch (Exception ex) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            logger.error("BMS_CheckTeamItemName", ex);
        }
        return wID;
    }

    public void BMS_UpdateTeamItem(BMSEmployee wLoginUser, BMSTeamItem wTeamItem, OutResult<Integer> wErrorCode) {
        wErrorCode.set(0);

        try {

            if (wTeamItem == null || StringUtils.isEmpty(wTeamItem.Name) || wTeamItem.TeamID <= 0) {

                wErrorCode.set(ExceptionTypes.Parameter.getValue());
                return;
            }

            int wCheckID = this.BMS_CheckTeamItemName(wLoginUser, wTeamItem, wErrorCode);
            if (wCheckID > 0) {
                wErrorCode.set(ExceptionTypes.Duplication.getValue());
                return;
            }

            Map<String, Object> wParams = new HashMap<String, Object>();

            wParams.put("Name", wTeamItem.Name);
            wParams.put("WorkAreaID", wTeamItem.WorkAreaID);
            wParams.put("StationID", wTeamItem.StationID);
            wParams.put("EditorID", wLoginUser.getID());
            wParams.put("EditTime", Calendar.getInstance());
            wParams.put("Active", wTeamItem.Active);
            wParams.put("Description", wTeamItem.Description);
            wParams.put("MateID", StringUtils.Join(",", wTeamItem.MateID));

            if (wTeamItem.ID > 0) {

                wParams.put("ID", wTeamItem.ID);
                super.Update(super.getTableName("bms_teamitem"), "ID", wParams);
            } else {

                wParams.put("CreatorID", wLoginUser.getID());

                wParams.put("CreateTime", Calendar.getInstance());
                wParams.put("TeamID", wTeamItem.TeamID);
                wTeamItem.ID = super.Insert(super.getTableName("bms_teamitem"), wParams);
            }

        } catch (Exception ex) {
            logger.error("BMS_SaveTeamItem", ex);
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
        }

    }

    public void BMS_ActiveTeamItem(BMSEmployee wLoginUser, int wID, int wActive, OutResult<Integer> wErrorCode) {
        wErrorCode.set(0);

        try {

            if (wID <= 0) {
                return;
            }

            Map<String, Object> wParams = new HashMap<String, Object>();

            String wSQLText = StringUtils.Format(
                    "Update {0}.bms_teamitem Set  EditorID=:EditorID,EditTime=:EditTime,Active={1} where ID=:ID",
                    super.getDBName(), wActive == 1 ? 1 : 2);
            wParams.clear();

            wParams.put("EditorID", wLoginUser.getID());
            wParams.put("EditTime", Calendar.getInstance());
            wParams.put("ID", wID);
            wSQLText = this.DMLChange(wSQLText);
            super.update(wSQLText, wParams);

        } catch (Exception ex) {
            logger.error("BMS_ActiveTeamItem", ex);
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
        }
    }

    public List<BMSTeamItem> BMS_QueryTeamItemList(
            BMSEmployee wLoginUser, String wName, int wFactoryID, int wWorkTypeID, int wWorkshopID, int wTeamID,
            int wWorkAreaID, int wStationID, String wStationCode, int wActive, Pagination wPagination,
            OutResult<Integer> wErrorCode) {

        return this.BMS_QueryTeamItemList(wLoginUser, -1, wName, wFactoryID, wWorkTypeID, wWorkshopID, wTeamID,
                StringUtils.parseListArgs(wWorkAreaID), wStationID, wStationCode, wActive, wPagination, wErrorCode);
    }


    public List<BMSTeamItem> BMS_QueryTeamItemList(
            BMSEmployee wLoginUser, int wID, String wName, int wFactoryID, int wWorkTypeID, int wWorkshopID,
            int wTeamID, List<Integer> wWorkAreaID, int wStationID, String wStationCode, int wActive,
            Pagination wPagination, OutResult<Integer> wErrorCode) {
        wErrorCode.set(0);
        List<BMSTeamItem> wTeamItemList = new ArrayList<BMSTeamItem>();

        try {

            if (wWorkAreaID == null) {
                wWorkAreaID = new ArrayList<>();
            }
            wWorkAreaID.removeIf(p -> p <= 0);

            Map<String, Object> wParams = new HashMap<String, Object>();

            String wSQLText = StringUtils.Format(
                    "Select t.*,t1.Name as TeamName,t1.DepartmentID,t2.Name as DepartmentName," +
                    " t3.Name as CreatorName ,t4.Name as EditorName,t5.Name as FactoryName,ifnull(t6.Name,t61.Name) as WorkshopName," +
                    " ifnull(t7.Name,t71.Name) as StationName ,ifnull(t7.Code,t71.Code) as StationCode ," +
                    " ifnull(t8.Code,t81.Code) as WorkAreaCode,  ifnull(t8.Name,t81.Name) as WorkAreaName ,t9.Name as WorkTypeName," +
                    " group_concat(t10.Name) as MateName from {0}.bms_teamitem t " +
                    " left join {0}.bms_team t1 on t.TeamID=t1.ID " +
                    " left join {0}.bms_department t2 on t1.DepartmentID=t2.ID " +
                    " left join {0}.mbs_user t3 on t.CreatorID=t3.ID " +
                    " left join {0}.mbs_user t4 on t.EditorID=t4.ID " +
                    " left join {0}.fmc_factory t5 on t1.FactoryID=t5.ID " +
                    " left join {0}.bms_worktype t9 on t1.WorkTypeID=t9.ID " +
                    " left join {0}.fmc_workshop t6 on t9.WorkMode=:WorkShopMode and  t1.WorkshopID=t6.ID " +
                    " left join {0}.wms_store t61 on t9.WorkMode=:WorkStoreMode and  t1.WorkshopID=t61.ID " +
                    " left join {0}.fmc_workarea t8 on  t9.WorkMode=:WorkShopMode and  t.WorkAreaID=t8.ID " +
                    " left join {0}.wms_workregion t81 on t9.WorkMode=:WorkStoreMode and   t.WorkAreaID=t81.ID " +
                    " left join {0}.fmc_station t7 on  t9.WorkMode=:WorkShopMode and  t.StationID=t7.ID " +
                    " left join {0}.wms_storestation t71 on t9.WorkMode=:WorkStoreMode and  t.StationID=t71.ID " +
                    " left join {0}.mbs_user t10 on t10.Active=1 and Find_In_Set(t10.ID,t.MateID) " +
                    " where (:ID<=0 or  t.ID=:ID)  AND (:Active<0 or  t.Active=:Active) " +
                    " AND (:TeamID<=0 or  t.TeamID=:TeamID) " + "  AND (:FactoryID<=0 or  t1.FactoryID=:FactoryID) " +
                    " AND (:WorkTypeID<=0 or  t1.WorkTypeID=:WorkTypeID) " +
                    " AND (:WorkshopID<=0 or  t1.WorkshopID=:WorkshopID) " +
                    " AND (:StationID<0 or  t.StationID=:StationID) " +
                    " AND (:StationCode = '''' or  t7.Code = :StationCode or t71.Code = :StationCode) " +
                    " AND (:WorkAreaID = '''' or  t7.WorkAreaID in (''{1}'')) " +
                    " AND (:Name = '''' or  t.Name like :Name) group by ID", super.getDBName(),
                    StringUtils.Join("','", wWorkAreaID));
            wParams.clear();
            wParams.put("ID", wID);
            wParams.put("Active", wActive);
            wParams.put("Name", StringUtils.isEmpty(wName) ? "" : ("%" + wName + "%"));
            wParams.put("FactoryID", wFactoryID);
            wParams.put("WorkTypeID", wWorkTypeID);
            wParams.put("WorkshopID", wWorkshopID);
            wParams.put("TeamID", wTeamID);
            wParams.put("WorkAreaID", StringUtils.Join(",", wWorkAreaID));
            wParams.put("WorkShopMode", BMSWorkMode.WorkShop.getValue());
            wParams.put("WorkStoreMode", BMSWorkMode.Store.getValue());
            wParams.put("StationID", wStationID);
            wParams.put("StationCode", wStationCode);

            wSQLText = this.DMLChange(wSQLText);
            List<Map<String, Object>> wQueryResultList = super.queryForList(wSQLText, wParams, wPagination);

            BMSTeamItem wTeamItem = null;
            for (Map<String, Object> wSqlDataReader : wQueryResultList) {
                wTeamItem = new BMSTeamItem();
                wTeamItem.ID = StringUtils.parseInt(wSqlDataReader.get("ID"));
                wTeamItem.Name = StringUtils.parseString(wSqlDataReader.get("Name"));
                wTeamItem.Active = StringUtils.parseInt(wSqlDataReader.get("Active"));
                wTeamItem.TeamID = StringUtils.parseInt(wSqlDataReader.get("TeamID"));
                wTeamItem.TeamName = StringUtils.parseString(wSqlDataReader.get("TeamName"));
                wTeamItem.DepartmentID = StringUtils.parseInt(wSqlDataReader.get("DepartmentID"));
                wTeamItem.DepartmentName = StringUtils.parseString(wSqlDataReader.get("DepartmentName"));
                wTeamItem.FactoryID = StringUtils.parseInt(wSqlDataReader.get("FactoryID"));
                wTeamItem.FactoryName = StringUtils.parseString(wSqlDataReader.get("FactoryName"));
                wTeamItem.WorkshopID = StringUtils.parseInt(wSqlDataReader.get("WorkshopID"));
                wTeamItem.WorkshopName = StringUtils.parseString(wSqlDataReader.get("WorkshopName"));
                wTeamItem.WorkAreaID = StringUtils.parseInt(wSqlDataReader.get("WorkAreaID"));
                wTeamItem.WorkAreaName = StringUtils.parseString(wSqlDataReader.get("WorkAreaName"));
                wTeamItem.WorkAreaCode = StringUtils.parseString(wSqlDataReader.get("WorkAreaCode"));
                wTeamItem.StationID = StringUtils.parseInt(wSqlDataReader.get("StationID"));
                wTeamItem.StationName = StringUtils.parseString(wSqlDataReader.get("StationName"));
                wTeamItem.StationCode = StringUtils.parseString(wSqlDataReader.get("StationCode"));

                wTeamItem.WorkTypeID = StringUtils.parseInt(wSqlDataReader.get("WorkTypeID"));
                wTeamItem.WorkTypeName = StringUtils.parseString(wSqlDataReader.get("WorkTypeName"));
                wTeamItem.MateID = StringUtils.parseIntList(wSqlDataReader.get("MateID"), ",");
                wTeamItem.MateName = StringUtils.parseString(wSqlDataReader.get("MateName"));

                wTeamItem.CreatorID = StringUtils.parseInt(wSqlDataReader.get("CreatorID"));
                wTeamItem.EditorID = StringUtils.parseInt(wSqlDataReader.get("EditorID"));
                wTeamItem.CreatorName = StringUtils.parseString(wSqlDataReader.get("CreatorName"));
                wTeamItem.EditorName = StringUtils.parseString(wSqlDataReader.get("EditorName"));
                wTeamItem.CreateTime = StringUtils.parseCalendar(wSqlDataReader.get("CreateTime"));
                wTeamItem.EditTime = StringUtils.parseCalendar(wSqlDataReader.get("EditTime"));
                wTeamItem.Description = StringUtils.parseString(wSqlDataReader.get("Description"));

                if (StringUtils.isEmpty(wTeamItem.Code)) {
                    wTeamItem.Code = StringUtils.Format("BZR{0}", String.format("%06d", wTeamItem.ID));
                }
                wTeamItemList.add(wTeamItem);

            }
        } catch (Exception ex) {
            logger.error("BMS_QueryTeamItemList", ex);
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
        }
        return wTeamItemList;
    }

    public BMSTeamItem BMS_QueryTeamItem(BMSEmployee wLoginUser, int wID, OutResult<Integer> wErrorCode) {
        wErrorCode.set(0);
        BMSTeamItem wResult = new BMSTeamItem();

        try {

            if (wID <= 0) {
                return wResult;
            }

            List<BMSTeamItem> wList = this.BMS_QueryTeamItemList(wLoginUser, wID, "", -1, -1, -1, -1, null, -1, "", -1,
                    Pagination.getDefault(), wErrorCode);

            if (wList.size() > 0) {
                wResult = wList.get(0);
            }

        } catch (Exception ex) {
            logger.error("BMS_QueryTeamItemByID", ex);
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
        }
        return wResult;
    }

    public void BMS_DeleteTeamItem(BMSEmployee wLoginUser, BMSTeamItem wTeamItem, OutResult<Integer> wErrorCode) {
        wErrorCode.set(0);

        try {

            if (wTeamItem == null || wTeamItem.TeamID <= 0) {

                wErrorCode.set(ExceptionTypes.Parameter.getValue());
                return;
            }

            Map<String, Object> wParams = new HashMap<String, Object>();

            wParams.put("ID", wTeamItem.ID);
            super.Delete(super.getTableName("bms_teamitem"), wParams);

        } catch (Exception ex) {
            logger.error("BMS_SaveTeamItem", ex);
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
        }

    }


}
